package com.smasher.weight.unique;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.smasher.core.io.FileUtil;
import com.smasher.core.other.WeakReferenceHandler;
import com.smasher.core.thread.ThreadPool;

import java.io.File;
import java.io.IOException;

/**
 * @author smasher
 */
public class UniqueKeyHelper implements Handler.Callback {

    private final WeakReferenceHandler mHandler;
    private String mPath;
    private String mUniqueId;
    private String mUniqueIdTemp;
    private UniqueCallback mCallback;

    private static final int UNIQUE_GET = 99;


    private UniqueKeyHelper() {
        mHandler = new WeakReferenceHandler(this);
        mUniqueId = "";
        mUniqueIdTemp = "";
    }

    private static class SingletonInstance {
        private static final UniqueKeyHelper INSTANCE = new UniqueKeyHelper();
    }

    public static UniqueKeyHelper getInstance() {
        return SingletonInstance.INSTANCE;
    }

    public void init(Context context, int mode, UniqueCallback callback) {
        mPath = context.getFilesDir().getPath();
        UniqueDelegate mDelegate = getDelegateByMode(mode);
        mUniqueIdTemp = mDelegate.getUniqueId(context);
        mCallback = callback;
        mCallback.onStart();
        getUniqueTask();
    }

    /**
     * @param mode 0-AndroidId,1-macaddress
     * @return UniqueDelegate
     */
    private UniqueDelegate getDelegateByMode(int mode) {
        UniqueDelegate delegate;
        switch (mode) {
            case 0:
                delegate = new UniqueAndroidId();
                break;
            case 1:
                delegate = new UniqueMacAddress();
                break;
            default:
                delegate = new UniqueAndroidId();
                break;
        }
        return delegate;
    }


    @Override
    public boolean handleMessage(@NonNull Message msg) {
        int what = msg.what;
        if (what == UNIQUE_GET) {
            String unique = (String) msg.obj;
            if (TextUtils.isEmpty(unique)) {
                mUniqueId = mUniqueIdTemp;
                saveUniqueTask();
            } else {
                mUniqueId = unique;
            }
            if (mCallback != null) {
                mCallback.onGet();
            }
            return true;
        }
        return false;
    }


    private void getUniqueTask() {
        ThreadPool.getInstance(ThreadPool.PRIORITY_HIGH).submit(() -> {
            String infoPath = mPath.concat(File.separator).concat("unique");
            File file = new File(infoPath);
            if (!file.exists()) {
                try {
                    boolean isSuccess = file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String unique = FileUtil.loadFile(file);

            if (mHandler != null) {
                Message message = Message.obtain();
                message.what = UNIQUE_GET;
                message.obj = unique;
                mHandler.sendMessage(message);
            }
        });
    }


    private void saveUniqueTask() {
        ThreadPool.getInstance(ThreadPool.PRIORITY_HIGH).submit(() -> {
            String infoPath = mPath.concat(File.separator).concat("unique");
            File file = new File(infoPath);
            if (file.exists()) {
                try {
                    boolean isDelete = file.delete();
                    Boolean isCreate = file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileUtil.saveFile(file, mUniqueId);
        });
    }


    public String getUniqueId() {
        return mUniqueId;
    }
}